/* eslint-disable prettier/prettier */
/**
 * 入参
 *  type：1-指令新增   2-簿记新增    3-详情  4-交收
    info：type=3||4时，需回填字段
    onRef：组件指针
    getInfo：通过onRef，调用getInfo方法，获取各字段的值，在getInfo中完成校验，若校验不通过，返回undefined
    reset：通过onRef，调用reset方法，清空页面字段
    productOnChange：产品变更事件，输出当前产品ID，若无则为undefined；
    portfolioOnChange：组合变更事件，输出当前组合ID，若无则为undefined；
    tradingcodeOnChange：证券代码变更事件，输出当前证券code，若无则为undefined。
 */
import React, { PureComponent } from 'react';
import { PrimaryC, ModalC, PrimaryGhostC, TableC } from '../../../../components';
import { message, } from 'antd';
import style from './index.less';
import { connect } from 'dva';
import OrderFormC from './orderFormC';
import { uniqueKey, AutomaticSettlement } from '../../../../utils/commonFunc';
import OrderC from '../../../../comps/business/orderC';

class AddOrderC extends PureComponent {
  static defaultProps = {
    portfolioOnChange: () => {},
    productOnChange: () => {},
    tradingcodeOnChange: () => {},
    productGroupOnChange:()=>{},
    onChangePortfolioCode:()=>{},
    changeTimeStamp:()=>{},
    onCancel:()=>{},
    onOk:()=>{},
    position:{},
    money:{},
    onRef:()=>{},
  };

  state = {
    info: undefined, // 详情
    type: undefined, // 当前指令的类型type：1-指令新增   2-簿记新增    3-簿记详情
    isShow: false, // 二次确认模态框显示隐藏
    querys: {}, // 二次确认详情数据
    isCanOrder: true, // 组合是否可以下达 默认可以
    trailColumns: [], // 试算结果列表
    trailDataSource: [], // 试算结果数据
    trailModel: false, // 试算模态框
    productCode: undefined, // 产品code
    portfolioCode: undefined, // 组合code
  };

  componentDidMount() {
    this.props.onRef(this);
    if (this.props.type == 1 || this.props.type == 12) {
      // 指令下达 簿记下达 时候需要
      const uid = uniqueKey();
      uid.then((r) => {
        this.setState({ uid: r });
      });
    }
  }

  // 用户点击下达或确定按钮
  onOk = () => {
    const { type, money, position } = this.props;
    if (!this.state.isCanOrder && type == 1) {
      message.warning(this.props.errorSetMsg);
      return;
    }
  this.orderForm.getInfo().then((data)=>{
    console.log('data',data)
    // 校验页面数据
    if (!data) return;
    data.uid = this.state.uid;
    if (type !== 10 && type !== 2) {
      // 交易录入和簿记不进行校验
      if (data.direction == 1) {
        if (parseFloat(money.t0 || 0) < parseFloat(data.parValueTotal)) {
          message.error('交易总额不能大于t+0可用!');
          return;
        }
      }
      if (data.direction == 2) {
        if (parseFloat(position.available || 0) - parseFloat(data.amount) < 0) {
          message.error('交易数量不能大于可用数量!');
          return;
        }
      }
    }
    if (type == 1) {
      if (this.state.isShow) {
        this.confirmOk(data); // 二次确认的确定 点击按钮
      } else {
        // 指令下达需要二次确认
        this.setState({
          querys: data,
          isShow: true,
        });
      }
    } else {
      // 簿记无需二次确认 直接请求后端
      this.confirmOk(data);
    }
    });
    
  };

  // 用户点击取消
  onCancel = () => {
    this.orderForm.reset();
    this.setState({
      isCanOrder: true,
    });
    this.props.onCancel();
  };

  confirmOk = (params) => {
    // 指令下达 簿记保存请求后台
    const { dispatch, type } = this.props;
    let url = '';
    // eslint-disable-next-line default-case
    switch (type) {
      // 指令
      case 1 || '1':
        url = 'nonstandardOrderM/orderSave';
        break;
      // 簿记
      case 2 || '2':
        url = 'nonstandardOrderM/tradeBookSave';
        break;
      // 存续管理
      case 10 || '10':
        url = 'nonstandardOrderM/tradeAdd';
        break;
      // 组合试算
      case 11 || '11':
        url = 'portfolioTrialAddM/nonstandardOrderSave';
        break;
      // 多基金
      case 12 || '12':
        url = 'moreFundsOrderM/nonstandardAdd';
        break;
    }
    if (type == 2) {
      // 簿记下达
      this.saveOrderNew(params);
      return;
    }
    if (type == 2 || type == 10 || type == 12) {
      // 簿记下达 交易录入 多基金指令
      params.method = '0';
      params.tradeInstruction = { direction: params.direction, stockCode: params.tradingcode };
    }
    if (type == 10) {
      // 交易录入 需要
      params.productid = params.portfolioid;
    }
    if (type == 11) {
      // 组合试算 需要
      params.type = '12';
    }
    
   
    dispatch({
      type: url,
      payload: {
        ...params,
      },
      callback: (res) => {
        if (res && res.success) {
          if (type == 2 || type == 10 || type == 11 || type == 12) {
            // 簿记下达成功
            this.props.onOk();
            this.onCancel(); // 初始化form表单
          } else {
            // 指令下达成功
            this.onCancel(); // 初始化form表单
            this.handleCancel(); // 关闭模态框
          }
          if (type == 12) {
            return;
          }
          message.success(type == 1 ? '指令下达成功!' : type == 2 ? '簿记下达成功!' : type == 11 ? '组合试算下达成功！' : '交易录入成功!');
        } else {
          if (type == 12) {
            return;
          }
          message.error(res ? res.message : type == 1 ? '指令下达失败!' : type == 2 ? '簿记下达失败!' : type == 11 ? '组合试算下达失败！' : '交易录入失败!');
        }
        if (this.props.type == 1) {
          const uid = uniqueKey();
          uid.then((r) => {
            this.setState({ uid: r });
          });
        }
      },
    });
  };

  // 簿记下达
  saveOrderNew = (args) => {
    const { type } = this.props;
    const { productCode, productName, portfolioCode, portfolioName } = this.state;
    if (type == 2) {
      const params = {
        productCode, // 产品code
        productId: args.productid, // 产品id
        productName, // 产品名称
        portfolioCode, // 组合code
        portfolioId: args.portfolioid, // 组合id
        portfolioName, // 组合名称
        tradingCode: args.tradingcode, // 证券代码
        tradingName: args.secuabbr, // 证券名称
        exchangeCode: args.exchangeCode, // 交易市场
        tradeDir: args.direction, // 交易方向
        price: args.price, // 价格
        num: args.amount, // 数量
        amount: args.parValueTotal, // 交易总额
        investmentType: args.investmentType, // 投资类型
        remark: args.remark, // 备注
        instructionType: '0', // 0是指簿记
        userDefinedType:args.userDefinedType,// 自定义分类 
        businessObjectives:args.bussinessObjectives,// 业务目标
        sppiResult:args.sppiResult,// SPPI结果
        isRelatedInterest:args.isRelatedInterest,// 绩效评估是否与利息收入合同报酬相关数据选择
        isRelatedValue:args.isRelatedValue,// 绩效评估是否与公允价值处分损益相关
        isCurrentYearHandle:args.isCurrentYearHandle,// 最近一年是否有处置
        lastHandleDate:args.lastHandleDate,// 最近一次处置时间
        reason:args.reason,// 处分原因
        interest:args.interest,// 利息
        interestArrivalDate:args.interestArrivalDate,// 利息到账日
      };
      // 判断租户是否配置自动交收，若配置自动交收给予弹窗提醒
      if (
        AutomaticSettlement(type, undefined, undefined, undefined, () => {
          console.log('自动交收');
          this.setState({
            orderParams: params,
            visibleStep: true,
          });
        })
      ) {
        return;
      }
      // 没有自动交收
      this.setState({
        orderParams: params,
        visibleStep: true,
      });
    }
  };

   // 下达成功之后  清空页面
   handleSuccess = () => {
    this.setState({
      visibleStep: false,
    });
    // 恢复默认状态
    this.onCancel();
  };

  // 下达失败 用户主动点击关闭 处理逻辑
  handleError = (type) => {
    this.setState({
      visibleStep: false,
    });
    if (type) {
      // 更新可用持仓 还是可用资金
      this.props.changeTimeStamp(type == 1 ? 'timeStamp1' : 'timeStamp2');
    }
  };


  // 二次确认取消按钮 关闭模态框
  handleCancel = () => {
    this.setState({
      isShow: false,
      querys: {},
    });
  };

  // 二次确认modal框
  showModal = () => {
    const { querys, isShow } = this.state;
    const { loading } = this.props;
    const modalProps = {
      visible: isShow,
      title: '确认指令下达',
      width: 700,
      height: 1000,
      className: 'confirmOrder',
      confirmLoading: loading.effects['nonstandardOrderM/orderSave'] === true,
    };
    return (
      <ModalC {...modalProps} onOk={this.onOk} onCancel={this.handleCancel}>
        <OrderFormC type={'3'} info={querys} />
      </ModalC>
    );
  };

  queryIsAccountConfigured = (value) => {
    if (value) {
      this.props.dispatch({
        // 校验组合下是否有组合配置
        type: 'isAccountConfiguredM/queryIsAccountConfigured',
        payload: {
          portId: value,
        },
        callback: (data) => {
          if (data.result) {
            this.setState({
              isCanOrder: true,
            });
          } else {
            this.setState({
              isCanOrder: false,
            });
            message.warning(data.msg);
          }
        },
      });
    } else {
      this.setState({
        isCanOrder: true,
      });
    }
  };

  // 试算按钮点击
  trialOnClick = () => {
    const {
      type,
      money,
      position,
      dispatch,
      user: { currentUser = {} },
    } = this.props;
    const data = this.orderForm.getInfo();
    // 校验页面数据
    if (!data) return;
    if (type !== 10) {
      // 交易录入不进行校验
      if (data.direction == 1) {
        if (parseFloat(money.t0 || 0) < parseFloat(data.parValueTotal)) {
          message.error('交易总额不能大于t+0可用!');
          return;
        }
      }
      if (data.direction == 2) {
        if (parseFloat(position.available || 0) - parseFloat(data.amount) < 0) {
          message.error('交易数量不能大于可用数量!');
          return;
        }
      }
    }
    if (type == 2) {
      // 簿记下达
      data.method = '0';
      data.tradeInstruction = { direction: data.direction, stockCode: data.tradingcode };
    }
    const querys = {
      productCode: this.state.productCode, // 产品code
      portfolioCode: this.state.portfolioCode, // 组合code
      tenant: currentUser.tenant, // 租户code
      businessType: '12',
      type: '12',
      trade12: data,
    };
    this.setState({ trailModel: true }, () => {
      dispatch({
        type: 'trailM/trialData',
        payload: querys,
        callback: (res) => {
          if (res) {
            this.setState({
              trailColumns: res.columns,
              trailDataSource: res.dataSource,
            });
          } else {
            this.setState({
              trailColumns: [],
              trailDataSource: [],
            });
          }
        },
      });
    });
  };

  // 试算结果列表优化
  trailColumnsChange = (data) => {
    if (data) {
      data?.map((item) => {
        if (item.key == 'ruleDesc') {
          item.ellipsis = true;
        } else {
          item.width = '125px';
        }
      });
    }
    return data;
  };

  // 试算结果
  showTrail = () => {
    const { trailModel, trailColumns, trailDataSource } = this.state;
    const newTrailColumns = this.trailColumnsChange(trailColumns);
    return (
      <ModalC
        visible={trailModel}
        title='试算结果'
        width={1200}
        onOk={() => {
          this.setState({ trailModel: false });
        }}
        onCancel={() => {
          this.setState({ trailModel: false });
        }}
      >
        <TableC
          columns={newTrailColumns}
          dataSource={trailDataSource}
          loading={this.props.loading.effects['trailM/trialData'] === true}
          scroll={{ y: '231px' }}
          rowKey='id'
          hidePage={true}
        />
      </ModalC>
    );
  };

  // 获取组合code
  portfolioCode = (e) => {
    if (e) {
      this.setState({ portfolioCode: e?.info?.portfolioCode, portfolioName: e?.info?.portfolioName });
    } else this.setState({ portfolioCode: undefined ,portfolioName:undefined});
      this.props.onChangePortfolioCode(e?.info?.portfolioCode);
  };

  // 获取产品code
  productCode = (e) => {
    if (e) {
      this.setState({ productName: e?.info?.portfolioName, productCode: e?.info?.portfolioCode });
    } else this.setState({ productCode: undefined ,productName:undefined});
  };

  render() {
    const { loading } = this.props;
    const { visibleStep, orderParams } = this.state;
    return (
      <div>
        <div className={'backBg'}>
          <OrderFormC
           { ...this.props}
            type={this.props.type}
            portfolioOnChange={(e) => {
              this.props.portfolioOnChange(e);
              if (this.props.type == '1') this.queryIsAccountConfigured(e); // 指令下达的时候进行校验组合是否配置
            }}
            productGroupOnChange={this.props.productGroupOnChange}
            tradingcodeOnChange={this.props.tradingcodeOnChange}
            listId={this.props.listId}
            portfolioCode={this.portfolioCode}
            productCode={this.productCode}
            onRef={(ref) => {
              this.orderForm = ref;
            }}
            investmentType={this.props.type > 3 && this.props.type != 12 ? undefined : this.props.position.investmentType}
          />
        </div>
       { this.props.workStation?null:<div style={{ marginTop: '20px' }} className={style.btnOperate}>
          <PrimaryC
            loading={
              loading.effects['portfolioTrialAddM/nonstandardOrderSave'] === true ||
              loading.effects['nonstandardOrderM/tradeBookSave'] === true ||
              loading.effects['nonstandardOrderM/tradeAdd'] === true ||
              loading.effects['moreFundsOrderM/nonstandardAdd'] === true
              ||visibleStep===true
            }
            onClick={this.onOk}
            title={this.props.type == 1 ? '下达' : '确定'}
          />
          <PrimaryGhostC onClick={this.onCancel} title='取消' style={{ marginLeft: '10px' }} />
        </div>}
        {this.state.isShow ? <div>{this.showModal()}</div> : null}
        {this.state.trailModel && this.showTrail()}
        {visibleStep ? 
        <OrderC 
        visible={visibleStep} 
        handleSuccess={this.handleSuccess}
         handleError={this.handleError} 
         params={orderParams} tradeType={'nonStandBj'} 
         /> : null}
      </div>
    );
  }
}
export default connect(({ nonstandardOrderM, userM: user, portfolioTrialAddM, loading, trailM, isAccountConfiguredM, moreFundsOrderM }) => ({
  nonstandardOrderM,
  user,
  portfolioTrialAddM,
  loading,
  trailM,
  errorSetMsg: isAccountConfiguredM.msg,
  isAccountConfiguredM,
  moreFundsOrderM,
}))(AddOrderC);
